package com.turbo.cloud.core.trace;

import cn.hutool.core.util.StrUtil;
import com.turbo.cloud.core.utils.ApplicationContextHolder;
import com.turbo.cloud.core.utils.CustomizerIdUtil;


import java.util.Objects;
import java.util.UUID;

public class TraceThreadLocal {

    /**
     * 把构造函数私有，外面不能new，只能通过下面两个方法操作
     */
    private TraceThreadLocal() {

    }

    /**
     * 区分服务实例
     */
    public static final String HOST_ID = "HOST-" + UUID.randomUUID().toString().substring(25);

    /**
     * 服务名称
     */
    private static String serviceName;

    /**
     * traceId 自动继承父线程参数
     */
    private static final ThreadLocal<String> TRACE_ID = new ThreadLocal<>();
    /**
     * clientId 自动继承父线程参数
     */
    private static final ThreadLocal<String> CLIENT_ID = new ThreadLocal<>();
    /**
     * currentUser 自动继承父线程参数
     */
    private static final ThreadLocal<String> CURRENT_USER = new ThreadLocal<>();

    public static void setTraceId(String traceId) {
        TRACE_ID.set(traceId);
    }

    public static String getTraceId() {
        if (StrUtil.isBlank(TRACE_ID.get())) {
            setTraceId(CustomizerIdUtil.id("TRC-", null));
        }
        return TRACE_ID.get();
    }

    public static void setClientId(String traceId) {
        CLIENT_ID.set(traceId);
    }

    public static String getClientId() {
        if (StrUtil.isBlank(CLIENT_ID.get())) {
            setClientId(CustomizerIdUtil.id("CLIENT-", null));
        }
        return CLIENT_ID.get();
    }


    public static void setCurrentUser(String currentUser) {
        CURRENT_USER.set(currentUser);
    }

    public static String getCurrentUser() {
        return Objects.isNull(CURRENT_USER.get()) ? "NONE" : CURRENT_USER.get();
    }

    public static String getServiceName() {
        if (StrUtil.isBlank(serviceName)) {
            serviceName = ApplicationContextHolder.getApplicationContext().getEnvironment().getProperty("spring.application.name");
        }
        return serviceName;
    }

    public static void remove() {
        TRACE_ID.remove();
        CLIENT_ID.remove();
        CURRENT_USER.remove();
    }
}
